package GOrden.mobile;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.provider.MediaStore.Images.Media;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class ShowOrdenActivity extends Activity implements OnClickListener {

	private ProgressDialog progressDialog;
	private String ReceiveServer = "";
	private String orden;
	private String tipo;

	


	private final Handler progressHandler = new Handler() {

		public void handleMessage(Message msg) {
			if (msg.obj != null) {
				ReceiveServer = (String) msg.obj;
				ShowMensaje(ReceiveServer);
			}
			progressDialog.dismiss();
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.show_orden);
		Bundle bn = getIntent().getExtras();
		TextView txtTipo = (TextView) findViewById(R.id.txtTipo);
		txtTipo.setText(bn.getString("tipo"));
		TextView txtOrden = (TextView) findViewById(R.id.txtOrden);
		txtOrden.setText(bn.getString("orden"));
		this.orden = bn.getString("orden");
		TextView txtDireccion = (TextView) findViewById(R.id.txtDireccion);
		txtDireccion.setText(bn.getString("direccion"));
		TextView txtRefDir = (TextView) findViewById(R.id.txtDirReferencia);
		txtRefDir.setText(bn.getString("dir_referencia"));
		TextView txtDepartamento = (TextView) findViewById(R.id.txtDepartamento);
		txtDepartamento.setText(bn.getString("departamento"));
		TextView txtMunicipio = (TextView) findViewById(R.id.txtMunicipio);
		txtMunicipio.setText(bn.getString("municipio"));
		TextView txtBarrio = (TextView) findViewById(R.id.txtBarrio);
		txtBarrio.setText(bn.getString("barrio"));
		TextView txtCliente = (TextView) findViewById(R.id.txtCliente);
		txtCliente.setText(bn.getString("cliente"));
		TextView txtNic = (TextView) findViewById(R.id.txtNic);
		txtNic.setText(bn.getString("nic"));
		TextView txtMedidor = (TextView) findViewById(R.id.txtMedidor);
		txtMedidor.setText(bn.getString("medidor"));
		TextView txtMarca = (TextView) findViewById(R.id.txtTipoMedido);
		txtMarca.setText(bn.getString("marca"));
		TextView txtDeuda = (TextView) findViewById(R.id.txtDeuda);
		txtDeuda.setText(bn.getString("deuda"));
		TextView txtFacturas = (TextView) findViewById(R.id.txtFacturas);
		txtFacturas.setText(bn.getString("facturas"));

		Button btCancelar = (Button) findViewById(R.id.BtnCancelar);
		btCancelar.setOnClickListener(this);
		Button btConfirmar = (Button) findViewById(R.id.BtnConfirmar);
		btConfirmar.setOnClickListener(this);
		Button btResolver = (Button) findViewById(R.id.BtnResolver);
		btResolver.setOnClickListener(this);

		Button btVisita = (Button) findViewById(R.id.cmdVisita);
		btVisita.setOnClickListener(this);
		
		if (bn.getString("confirm").equals("1")) {
			btConfirmar.setEnabled(false);

		} else {
			btResolver.setEnabled(false);
			btVisita.setEnabled(false);
		}

	}

	public void onClick(View v) {
		// TODO Auto-generated method stub
		if (v.getId() == R.id.BtnConfirmar) {
			LoadData();
		} else if (v.getId() == R.id.BtnResolver) {

			Intent intent = new Intent(ShowOrdenActivity.this,
					ResolverOrdenActivity.class);
			Bundle bn = getIntent().getExtras();
			intent.putExtra("orden", bn.getString("orden"));
			intent.putExtra("tipo", bn.getString("tipo"));
			startActivityForResult(intent, 10);


		} else if (v.getId() == R.id.BtnCancelar) {
			finish();
		} else if (v.getId() == R.id.cmdVisita) {
			Intent intent = new Intent(ShowOrdenActivity.this,
					VisitaFallidaActivity.class);
			intent.putExtra("orden", this.orden);
			startActivityForResult(intent, 11);
			
		}

	}

	private void ShowMensaje(String data) {
		if (data.equals("OK")) {
			data = "Orden de servicio Confirmada";
			Toast toast = Toast.makeText(getApplicationContext(), data, Toast.LENGTH_LONG);
			toast.show();
			finish();
		} else { // error al confirmar la orden
			AlertDialog alert =  (AlertDialog) this.crearDialogoAlerta(data);
			alert.show();
		}

	}

	private void LoadData() {
		progressDialog = ProgressDialog.show(ShowOrdenActivity.this, "",
				"Por favor espere mientras se envian los datos...", true);

		new Thread(new Runnable() {
			public void run() {
				ConfirmarOrden conn = new ConfirmarOrden(
						"http://siscos.fcr.com.co:8080/movilidad/ConfirmOrder?orden="
								+ orden);
				Message msg = progressHandler.obtainMessage();
				msg.obj = conn.Confirmar(orden);
				progressHandler.sendMessage(msg);
			}
		}).start();
	}

	private Dialog crearDialogoAlerta(String mensaje) {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle("Informacion");
		builder.setMessage(mensaje);
		builder.setCancelable(false);
		builder.setPositiveButton("OK", new android.content.DialogInterface.OnClickListener() {
			
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				dialog.cancel();
			}
		});		
		return builder.create();
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		System.out.print("Request Code:" + requestCode);
		System.out.print("Result Code:" + resultCode);
		
		if (resultCode == RESULT_OK && requestCode == 10 ) {
			
			if (data.getStringExtra("resultado").equals("RESUELTA")) {
				finish();
			}
			
		}else if (resultCode == RESULT_OK && requestCode == 11 ) {
			if (data.getStringExtra("resultado").equals("FALLIDA")) {
				finish();
			}
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.menu_orden, menu);
		return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
	    // Handle item selection
	    switch (item.getItemId()) {
	        case R.id.MenuGeo:
	        	Intent intent = new Intent(ShowOrdenActivity.this,
						Camera.class);
				Bundle bn = getIntent().getExtras();
				intent.putExtra("orden", bn.getString("orden"));
				startActivity(intent);
	            return true;
	        case R.id.MenuMapa:
	            
	            return true;
	        default:
	            return super.onOptionsItemSelected(item);
	    }
	}
	
	
	
	
	
	
}
